import commonService from '@/services/common'; // 假设新的服务接口已经定义好
import studentService from '@/services/student'; // 假设新的服务接口已经定义好

import React, { createRef, useEffect, useState } from 'react';
import { Button, Col, DatePicker, Drawer, Form, Input, InputNumber, Row, Select, Space } from 'antd';
import { Radio } from 'antd/lib';

const { Option } = Select;

const { listCourseTypes, listMajors, listClassrooms, listTeachersByMajorId } =
  commonService.CommonController;

const { queryStudentByCardId } =
  studentService.StudentController;

export interface CreateFormValueType extends Partial<TeacherAPI.UpdateTeacherParam> {
  // 教师ID
  teacherId: string;
  // 学生ID
  studentId: string;
  // 教室ID
  classroomId: string;
  // 课程类型
  courseType: string;
  // 科目
  major: string;
  // 上课时间
  startTime: Date;
  // 下课时间
  endTime: Date;
  // 消课数
  courseUsedCount: number;
  // 备注
  comment: string;
}

export interface FormProps {
  visible: boolean;
  onCancel: () => void;
  onSubmit: (values: CreateFormValueType) => Promise<void>;
}




const App: React.FC<FormProps> = (props) => {

  const [form] = Form.useForm();

  const [courseTypes, setCourseTypes] = useState<CommonAPI.SimpleVL[]>([]);
  const [majors, setMajors] = useState<CommonAPI.SimpleVL[]>([]);
  const [teachers, setTeachers] = useState<CommonAPI.SimpleVL[]>([]);
  const [classrooms, setClassrooms] = useState<CommonAPI.SimpleVL[]>([]);

  const fetchTeachersByMajorId = async (majorId) => {
    try {
      const response = await listTeachersByMajorId({
        majorId,
      });
      const teachers = response.data.result;
      if (teachers) {
        const simpleVL = teachers.map(teacher => ({
          value: teacher.teacherId,
          label: teacher.teacherName,
        }));
        console.log(simpleVL);
        setTeachers(simpleVL);
      }
    } catch (error) {
      console.error('Failed to fetch majors:', error);
    }
  };

  useEffect(() => {
    const fetchCourseTypes = async () => {
      try {
        const response = await listCourseTypes();
        const courseTypes = response.data.result;
        if (courseTypes) {
          const simpleVL = courseTypes.map(courseType => ({
            value: courseType.courseTypeId,
            label: courseType.courseTypeName,
          }));
          console.log(simpleVL);
          setCourseTypes(simpleVL);
        }
      } catch (error) {
        console.error('Failed to fetch majors:', error);
      }
    };
    fetchCourseTypes();

    const fetchMajors = async () => {
      try {
        const response = await listMajors();
        const majorList = response.data.result;
        if (majorList) {
          const simpleVL = majorList.map(major => ({
            value: major.majorId,
            label: major.majorName,
          }));
          console.log(simpleVL);
          setMajors(simpleVL);
        }
      } catch (error) {
        console.error('Failed to fetch majors:', error);
      }
    };
    fetchMajors();

    const fetchClassrooms = async () => {
      try {
        const response = await listClassrooms();
        const classrooms = response.data.result;
        if (classrooms) {
          const simpleVL = classrooms.map(classroom => ({
            value: classroom.classroomId,
            label: classroom.classroomName,
          }));
          console.log(simpleVL);
          setClassrooms(simpleVL);
        }
      } catch (error) {
        console.error('Failed to fetch majors:', error);
      }
    };
    fetchClassrooms();

  }, []);


  const cardIdRef = createRef();
  const handleCardIdChange = (event) => {
    if (event.key === 'Enter' && !event.shiftKey) {
      const fetchStudentName = async () => {
        try {
          const cardId = cardIdRef.current.input.value;
          const response = await queryStudentByCardId({cardId});
          const student = response.data;
          form.setFieldValue('studentName', student.name);
        } catch (error) {
          console.error('Failed to fetch majors:', error);
        }
      };
      fetchStudentName();
    }
  };


  return (
    <>
      <Drawer
        title="划课记录"
        width={540}
        onClose={() => props.onCancel()}
        open={props.visible}
        styles={{
          body: {
            paddingBottom: 80,
          },
        }}
        extra={
          <Space>
            <Button onClick={() => props.onCancel()}>取消</Button>
            <Button onClick={() => props.onSubmit(form.getFieldsValue())} type="primary">
              提交
            </Button>
          </Space>
        }
      >
        <Form
          layout="vertical"
          form={form}
        >
          <Row gutter={16}>
            <Col span={24}>
              <Form.Item
                name="cardId"
                label="会员卡号"
                rules={[{ required: true, message: '请输入会员卡号' }]}
              >
                <Input
                  ref={cardIdRef}
                  onKeyPress={handleCardIdChange}
                  placeholder="请输入会员卡号"
                />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                name="studentName"
                label="学生姓名"
                rules={[{ required: true, message: '请输入会员卡号' }]}
              >
                <Input
                  disabled
                />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                name="courseTypeId"
                label="课程类型"
                rules={[{ required: true, message: '请输入会员卡号' }]}
              >
                <Radio.Group
                  options={courseTypes}
                />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                name="majorId"
                label="科目"
                rules={[{ required: true, message: '请输入会员卡号' }]}
              >
                <Radio.Group
                  onChange={(e) => fetchTeachersByMajorId(e.target.value)}
                  options={majors}
                />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                name="teacherId"
                label="教师"
                rules={[{ required: true, message: '请输入会员卡号' }]}
              >
                <Radio.Group
                  options={teachers}
                />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                name="classroomId"
                label="教室"
                rules={[{ required: true, message: '请输入会员卡号' }]}
              >
                <Radio.Group
                  options={classrooms}
                />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                name="startTime"
                label="上课时间"
                rules={[{ required: true, message: '请输入出生日期' }]}
              >
                <DatePicker
                  showTime
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                name="endTime"
                label="下课时间"
                rules={[{ required: true, message: '请输入出生日期' }]}
              >
                <DatePicker
                  showTime
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                name="courseUsedCount"
                label="划课数"
                rules={[{ required: true, message: '请输入划课数' }]}
              >
                <InputNumber
                  defaultValue={1}
                  placeholder="请输入划课数"
                />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item
                name="comment"
                label="备注"
              >
                <Input.TextArea rows={4} placeholder="请输入备注" />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Drawer>
    </>
  );
};

export default App;